package com.openbravo.pos.payment;

import com.openbravo.data.loader.LocalRes;
import com.openbravo.pos.forms.AppLocal;
import com.openbravo.pos.forms.AppProperties;
import com.openbravo.pos.util.AltEncrypter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class PaymentGatewayAuthorizeNet
  implements PaymentGateway
{
  private static String ENDPOINTADDRESS;
  private static final String OPERATIONVALIDATE = "AUTH_CAPTURE";
  private static final String OPERATIONREFUND = "CREDIT";
  private static final String APPROVED = "1";
  private String m_sCommerceID;
  private String m_sCommercePassword;
  private boolean m_bTestMode;

  public PaymentGatewayAuthorizeNet(AppProperties paramAppProperties)
  {
    this.m_sCommerceID = paramAppProperties.getProperty("payment.commerceid");
    AltEncrypter localAltEncrypter = new AltEncrypter(new StringBuilder().append("cypherkey").append(paramAppProperties.getProperty("payment.commerceid")).toString());
    this.m_sCommercePassword = localAltEncrypter.decrypt(paramAppProperties.getProperty("payment.commercepassword").substring(6));
    this.m_bTestMode = Boolean.valueOf(paramAppProperties.getProperty("payment.testmode")).booleanValue();
    ENDPOINTADDRESS = this.m_bTestMode ? "https://test.authorize.net/gateway/transact.dll" : "https://cardpresent.authorize.net/gateway/transact.dll";
  }

  public PaymentGatewayAuthorizeNet()
  {
  }

  public void execute(PaymentInfoMagcard paramPaymentInfoMagcard)
  {
    StringBuffer localStringBuffer = new StringBuffer();
    try
    {
      localStringBuffer.append("x_cpversion=1.0");
      localStringBuffer.append("&x_market_type=2");
      localStringBuffer.append("&x_device_type=1");
      localStringBuffer.append("&x_login=");
      localStringBuffer.append(URLEncoder.encode(this.m_sCommerceID, "UTF-8"));
      localStringBuffer.append("&x_tran_key=");
      localStringBuffer.append(URLEncoder.encode(this.m_sCommercePassword, "UTF-8"));
      localStringBuffer.append("&x_amount=");
      DecimalFormat localDecimalFormat = new DecimalFormat("0000.00");
      String str1 = localDecimalFormat.format(Math.abs(paramPaymentInfoMagcard.getTotal()));
      localStringBuffer.append(URLEncoder.encode(str1.replace(',', '.'), "UTF-8"));
      if (paramPaymentInfoMagcard.getTrack1(true) == null)
      {
        localStringBuffer.append("&x_card_num=");
        localStringBuffer.append(URLEncoder.encode(paramPaymentInfoMagcard.getCardNumber(), "UTF-8"));
        localStringBuffer.append("&x_exp_date=");
        String localObject1 = paramPaymentInfoMagcard.getExpirationDate();
        localStringBuffer.append(URLEncoder.encode((String)localObject1, "UTF-8"));
        String[] localObject2 = paramPaymentInfoMagcard.getHolderName().split(" ");
        localStringBuffer.append("&x_first_name=");
        if (localObject2.length > 0)
          localStringBuffer.append(URLEncoder.encode(localObject2[0], "UTF-8"));
        localStringBuffer.append("&x_last_name=");
        if (localObject2.length > 1)
          localStringBuffer.append(URLEncoder.encode(localObject2[1], "UTF-8"));
      }
      else
      {
        localStringBuffer.append("&x_track1=");
        localStringBuffer.append(paramPaymentInfoMagcard.getTrack1(false));
        localStringBuffer.append("&x_track2=");
        localStringBuffer.append(paramPaymentInfoMagcard.getTrack2(false));
      }
      localStringBuffer.append("&x_method=CC");
      localStringBuffer.append("&x_version=3.1");
      localStringBuffer.append("&x_delim_data=TRUE");
      localStringBuffer.append("&x_delim_char=|");
      localStringBuffer.append("&x_relay_response=FALSE");
      localStringBuffer.append("&x_test_request=");
      localStringBuffer.append(this.m_bTestMode);
      if (paramPaymentInfoMagcard.getTotal() >= 0.0D)
      {
        localStringBuffer.append("&x_type=");
        localStringBuffer.append("AUTH_CAPTURE");
      }
      else
      {
        localStringBuffer.append("&x_type=");
        localStringBuffer.append("CREDIT");
        localStringBuffer.append("&x_trans_id=");
        localStringBuffer.append(paramPaymentInfoMagcard.getTransactionID());
      }
      Object localObject1 = new URL(ENDPOINTADDRESS);
      Object localObject2 = ((URL)localObject1).openConnection();
      ((URLConnection)localObject2).setDoOutput(true);
      ((URLConnection)localObject2).setUseCaches(false);
      ((URLConnection)localObject2).setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      DataOutputStream localDataOutputStream = new DataOutputStream(((URLConnection)localObject2).getOutputStream());
      localDataOutputStream.write(localStringBuffer.toString().getBytes());
      localDataOutputStream.flush();
      localDataOutputStream.close();
      BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(((URLConnection)localObject2).getInputStream()));
      String str2 = localBufferedReader.readLine();
      localBufferedReader.close();
      AuthorizeNetParser localAuthorizeNetParser = new AuthorizeNetParser(str2);
      Map localMap = localAuthorizeNetParser.splitXML();
      if (localAuthorizeNetParser.getResult().equals(LocalRes.getIntString("button.ok")))
      {
        if ("1".equals(localMap.get("ResponseCode")))
        {
          paramPaymentInfoMagcard.paymentOK((String)localMap.get("AuthCode"), (String)localMap.get("TransID"), str2);
        }
        else
        {
          StringBuilder localStringBuilder = new StringBuilder();
          if (localAuthorizeNetParser.getNumErrors() > 0)
            for (int i = 1; i <= localAuthorizeNetParser.getNumErrors(); i++)
            {
              localStringBuilder.append(localMap.get(new StringBuilder().append("ErrorCode").append(Integer.toString(i)).toString()));
              localStringBuilder.append(": ");
              localStringBuilder.append(localMap.get(new StringBuilder().append("ErrorText").append(Integer.toString(i)).toString()));
              localStringBuilder.append("\n");
            }
          paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), localStringBuilder.toString());
        }
      }
      else
        paramPaymentInfoMagcard.paymentError(localAuthorizeNetParser.getResult(), "");
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), localUnsupportedEncodingException.getMessage());
    }
    catch (MalformedURLException localMalformedURLException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), localMalformedURLException.getMessage());
    }
    catch (IOException localIOException)
    {
      paramPaymentInfoMagcard.paymentError(AppLocal.getIntString("message.paymenterror"), localIOException.getMessage());
    }
  }

  private class AuthorizeNetParser extends DefaultHandler
  {
    private SAXParser m_sp = null;
    private Map props = new HashMap();
    private String text;
    private InputStream is;
    private String result;
    private int numMessages = 0;
    private int numErrors = 0;

    public AuthorizeNetParser(String arg2)
    {
      Object localObject;
      this.is = new ByteArrayInputStream(arg2.getBytes());
    }

    public Map splitXML()
    {
      try
      {
        if (this.m_sp == null)
        {
          SAXParserFactory localSAXParserFactory = SAXParserFactory.newInstance();
          this.m_sp = localSAXParserFactory.newSAXParser();
        }
        this.m_sp.parse(this.is, this);
      }
      catch (ParserConfigurationException localParserConfigurationException)
      {
        this.result = LocalRes.getIntString("exception.parserconfig");
      }
      catch (SAXException localSAXException)
      {
        this.result = LocalRes.getIntString("exception.xmlfile");
      }
      catch (IOException localIOException)
      {
        this.result = LocalRes.getIntString("exception.iofile");
      }
      this.result = LocalRes.getIntString("button.ok");
      return this.props;
    }

    public void endElement(String paramString1, String paramString2, String paramString3)
      throws SAXException
    {
      try
      {
        if (paramString3.equals("ResponseCode"))
        {
          this.props.put("ResponseCode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("ErrorCode"))
        {
          this.numErrors += 1;
          this.props.put("ErrorCode" + Integer.toString(this.numErrors), URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("ErrorText"))
        {
          this.props.put("ErrorText" + Integer.toString(this.numErrors), URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Code"))
        {
          this.numMessages += 1;
          this.props.put("Code" + Integer.toString(this.numMessages), URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("Description"))
        {
          this.props.put("Description" + Integer.toString(this.numMessages), URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("AuthCode"))
        {
          this.props.put("AuthCode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("AVSResultCode"))
        {
          this.props.put("AVSResultCode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("CVVResultCode"))
        {
          this.props.put("CVVResultCode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("TransID"))
        {
          this.props.put("TransID", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("RefTransID"))
        {
          this.props.put("RefTransID", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("TransHash"))
        {
          this.props.put("TransHash", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("TestMode"))
        {
          this.props.put("TestMode", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
        else if (paramString3.equals("UserRef"))
        {
          this.props.put("UserRef", URLDecoder.decode(this.text, "UTF-8"));
          this.text = "";
        }
      }
      catch (UnsupportedEncodingException localUnsupportedEncodingException)
      {
        this.result = localUnsupportedEncodingException.getMessage();
      }
    }

    public void startDocument()
      throws SAXException
    {
      this.text = new String();
    }

    public void endDocument()
      throws SAXException
    {
    }

    public void characters(char[] paramArrayOfChar, int paramInt1, int paramInt2)
      throws SAXException
    {
      if (this.text != null)
        this.text = new String(paramArrayOfChar, paramInt1, paramInt2);
    }

    public String getResult()
    {
      return this.result;
    }

    public int getNumErrors()
    {
      return this.numErrors;
    }

    public int getNumMessages()
    {
      return this.numMessages;
    }
  }
}

/* Location:           D:\PowerFulPOS-2.30.2\openbravopos.jar
 * Qualified Name:     com.openbravo.pos.payment.PaymentGatewayAuthorizeNet
 * JD-Core Version:    0.6.0
 */